package com.magicode.screen.share;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import com.magicode.screen.AppConfig;
import com.magicode.screen.AppContext;
import com.magicode.screen.R;
import com.magicode.screen.bean.Constants;
import com.magicode.screen.util.HTMLUtil;
import com.magicode.screen.util.TDevice;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by dell on 2016/12/9.
 */
public class ThirdPartyShareUtils {
    /**
     * 文字链接分享所用的参数
     */
    private String  shareContent;
    private String  shareUrl;
    private String  shareTitle;
    private String  shareSubject;
    private String  sharePicMinPath;
    private Activity shareActivity;
    private Context   context;
    /**
     * 分享
     */
    public void handleThirdPartyShare(String type) {
        if (TextUtils.isEmpty(shareContent)
                || TextUtils.isEmpty(shareUrl)) {
            Toast.makeText(context,"内容加载失败...", Toast.LENGTH_LONG).show();
            return;
        }

        switch (type) {
            case "circle":
                shareArticleToWx(1);//朋友圈
                break;
            case "weixin":
                shareArticleToWx(0);//微信
                break;
            case "weibo":
                shareToWeibo();
                break;
            case "qq":
                ShareQQ();
                break;
            case "copylink":
                TDevice.copyTextToBoard(shareUrl);
                break;
            case "more":
                TDevice.showSystemShareOption(shareActivity, shareTitle, shareUrl);
                break;
            default:
                break;
        }

    }

    /**
     * 微信分享
     */
    private IWXAPI api;

    /**
     * 网页类型
     * @param flag
     */
    private void shareArticleToWx(final int flag) {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(this.getContext(), AppConfig.APP_WX_KEY, false);
            api.registerApp(AppConfig.APP_WX_KEY);
        }
        if (!api.isWXAppInstalled()) {
            //提醒用户没有按照微信
            Toast.makeText(this.getContext(), "没有安装微信,请先安装微信!", Toast.LENGTH_SHORT).show();
            return;
        }

        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = shareUrl;
        WXMediaMessage msg = new WXMediaMessage(webPage);
        msg.title = shareTitle;
        msg.description = shareSubject;
        //这里替换一张自己工程里的图片资源
            Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_film);
        //     Bitmap thumb = convertStringToIcon(getSharePicMinPath());
        msg.setThumbImage(thumb);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
        api.sendReq(req);
    }
    /**
     * 图片类型
     * @param flag
     */
//    private void shareImageToWx(final int flag) {
//        Bitmap bmp=BitmapFactory.decodeResource(context.getResources(),R.drawable.icon_film);
//        //初始化
//        WXImageObject imgObj=new WXImageObject(bmp);
//        WXMediaMessage msg=new WXMediaMessage();
//        msg.mediaObject=imgObj;
//        //设置缩略图
//        Bitmap thumbBmp=Bitmap.createScaledBitmap(bmp,THUMB_SIZE,THUMB_SIZE,true);
//        bmp.recycle();
//        msg.thumbData= Util.bmpToByteArray(thumbBmp,true);
//        //构造一个Req
//        SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction= buildTransaction("img");//transaction 字段用于唯一表示一个请求
//        req.message=msg;
//        req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
//        api.sendReq(req);
//    }
    private IWeiboShareAPI iWeiboShareAPI;//微博

    private void shareToWeibo() {
        iWeiboShareAPI = WeiboShareSDK.createWeiboAPI(getContext(), Constants.APP_WB_KEY);//这里输入App Key
        iWeiboShareAPI.registerApp();//将应用注册到微博客户端
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected Void doInBackground(Void... params) {
                sendMultiMessageToWeibo(true, true);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
            }
        }.execute();
    }
    /**
     * 发送多种消息到微博
     *
     * @param hasText：是否有文本
     * @param hasImage：是否有图片
     */
    private void sendMultiMessageToWeibo(boolean hasText, boolean hasImage) {
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();//初始化微博的分享消息
        if (hasText) {
            weiboMessage.textObject = getTextObj();
        }
        if (hasImage) {
            // weiboMessage.mediaObject = getImageObj();
            weiboMessage.mediaObject = getWebpageObj();
        }
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;
        iWeiboShareAPI.sendRequest(this.shareActivity, request);//发送请求消息到微博，唤起微博分享界面
    }

    /**
     * 获取文本信息对象
     *
     * @return TextObject
     */
    private TextObject getTextObj() {
        TextObject textObject = new TextObject();
        textObject.text ="【"+shareTitle+"】"+ getFilterHtmlBody(shareSubject);//这里输入文本
        return textObject;
    }

    private WebpageObject getWebpageObj() {
        WebpageObject mediaObject = new WebpageObject();
        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = shareTitle;
        mediaObject.description = shareContent;
        URL url = null;
        // url = new URL("http://b.zol-img.com.cn/sjbizhi/images/9/320x510/1452499239911.jpeg");//这里输入图片地址
        try {
            url = new URL(sharePicMinPath);//这里输入图片地址
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = null;
        if (null != url) {
            try {
                bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                if (bitmap.getByteCount() > 4096000) {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = bitmap.getByteCount() / 4096000;//缩放比例
                    options.inJustDecodeBounds = false;
                    bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream(), null, options);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 设置 Bitmap 类型的图片到视频对象里         设置缩略图。 注意：最终压缩过的缩略图大小不得超过 32kb。
        mediaObject.setThumbImage(bitmap);
        mediaObject.actionUrl = shareUrl;
        mediaObject.defaultText = getContext().getString(R.string.app_name);
        return mediaObject;
    }

    private void ShareQQ() {
        Tencent mTencent = Tencent.createInstance(Constants.QQ_APPID, this.getApplication());
        if (mTencent.isSessionValid() && mTencent.getOpenId() == null) {
            Toast.makeText(this.getContext(), "没有安装QQ,请先安装QQ!", Toast.LENGTH_SHORT).show();
        }
        final Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, shareTitle);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, shareContent);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareUrl);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, sharePicMinPath);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME,  getContext().getString(R.string.app_name));
        //  params.putInt(QQShare.SHARE_TO_QQ_EXT_INT,  "其他附加功能");
        mTencent.shareToQQ(shareActivity, params, qqShareListener);
    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {
            Toast.makeText(getContext(), "发送取消 ", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            Toast.makeText(getContext(), "发送成功 ", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub
            Toast.makeText(getContext(), "发送失败 ", Toast.LENGTH_LONG).show();
        }
    };

    /***
     * 获取去除html标签的body
     *
     * @param body
     * @return
     */
    protected String getFilterHtmlBody(String body) {

        if (body == null)
            return "";
        return HTMLUtil.delHTMLTag(body.trim());
    }
    public AppContext getApplication() {
        return (AppContext) shareActivity.getApplication();
    }
    public String getShareContent() {
        return shareContent;
    }

    public void setShareContent(String shareContent) {
        this.shareContent = shareContent;
    }

    public String getShareUrl() {
        return shareUrl;
    }

    public void setShareUrl(String shareUrl) {
        this.shareUrl = shareUrl;
    }

    public String getShareTitle() {
        return shareTitle;
    }

    public void setShareTitle(String shareTitle) {
        this.shareTitle = shareTitle;
    }

    public String getShareSubject() {
        return shareSubject;
    }

    public void setShareSubject(String shareSubject) {
        this.shareSubject = shareSubject;
    }

    public String getSharePicMinPath() {
        return sharePicMinPath;
    }

    public void setSharePicMinPath(String sharePicMinPath) {
        this.sharePicMinPath = sharePicMinPath;
    }

    public Activity getShareActivity() {
        return shareActivity;
    }

    public void setShareActivity(Activity shareActivity) {
        this.shareActivity = shareActivity;
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }
}
